package com.sundaying.gooway.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharacterEncodingFilter implements Filter {
	protected FilterConfig filterConfig = null;         
    protected String encoding = "";
    
	@Override
	public void destroy() {
		filterConfig = null;    
        encoding = null;  
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		if (encoding != null) {
			System.out.println("重新设置页面encoding");
            //设置request和response的编程格式，注意两个都要设置
			//若没有设置response的charset，则在输出页面会显示乱码。 
            request.setCharacterEncoding(this.encoding);   
            response.setContentType("text/html;charset=utf-8");  
        }    
        //继续执行下一个过滤器  
        filterChain.doFilter(request, response); 
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("初始化过滤器CharacterEncodingFilter...");
		this.filterConfig = filterConfig;    
        this.encoding = filterConfig.getInitParameter("encoding");
        System.out.println("本站页面Encoding是：" + this.encoding);
	}

}
